package services;

import dao.UserInfoDao;
import models.UserInfo;
import utils.ResultJSONUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:咭咭熊
 * Date:2021 - 08 - 01
 * Time:17:39
 */
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int succ = -1;
        String msg = "登录成功！";
        //1.得到前端传递的参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //2.去数据库验证用户名和密码验证
        if(username != null && !username.equals("") && password != null && !password.equals("")){
            //参数正确，执行查询数据库
            UserInfoDao userInfoDao = new UserInfoDao();
            try {
                //查询数据库库
                UserInfo userInfo = userInfoDao.getUser(username,password);
                if(userInfo.getId() > 0){//说明查询到了用户
                    succ = 1;
                    //登录成功之后，将用户信息保存在session中
                    HttpSession session = request.getSession();
                    session.setAttribute("userinfo",userInfo);//将当前用户信息存放到session中；
                }else{
                    succ = 0;
                    msg = "用户名或者密码输入错误！";
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }else {
            //非法请求，参数不完整
            msg = "非法请求，参数不完整！";
        }
        //3.返回结果
        HashMap<String,Object> ret = new HashMap<>();
        ret.put("succ",succ);
        ret.put("msg",msg);
        ResultJSONUtils.write(response,ret);
    }
}
